<?php
class PharmaciesController extends AppController {

	var $name = 'Pharmacies';
	var $helpers = array('Html', 'Form','Paginator');
	var $uses = array('Pharmacy','Store','Vacancy','Locum','Apply','Event','Rate', 'Invite');
	var $components = array('Session','RequestHandler','Email','Image');
    
	function beforeFilter()
    {        
        parent::beforeFilter();
        // these action by pass authen
    	$a_ActionAccess = array( 'register', 'save' );
    	
    	// access these action if not login => redirect to login after back this action
        $a_ActionBack = array('view_locum_profile'); 
     	$user = $this->Session->read('User.User');
     	if ( !in_array($this->params['action'], $a_ActionAccess) )
     	{
     		
     		if ( $user )
     		{
     			if ( $user['UserType'] != 2 )
     				$this->redirect(array('controller'=>'errors','action' => 'permission'));
     		}
     		else 
     		{
     			if( in_array($this->params['action'], $a_ActionBack) )
     			{
     				$sz_BackPharUrl = 'http://' . $_SERVER['HTTP_HOST'] . $this->here;
     				$this->Session->write('sz_BackPharUrl', $sz_BackPharUrl);
     			}
     			$this->redirect(array('controller'=>'pages','action' => 'display'));
     		}
     	}
     	else 
     	{
     		if( $user )
     		{
     			$this->redirect(array('controller'=>'pharmacies','action' => 'view/' . $user['id']));
     		}
     	}
     	// Get my invite
     	$a_Invite = $this->Invite->v_fGetInviteByPharmacyId( $user['id'] );
     	$this->set('a_PharInvite', $a_Invite);
    }
	
	function index() {
        $UserInfo = $this->Session->read('User');
		$this->Pharmacy->recursive = 0;
       
		if(empty($UserInfo) || $UserInfo['User']['UserType'] !=2)
        {
            $this->redirect(array('controller'=>'pages','action' => 'display'));
        }
        
        $this->set('a_Stores', $this->Store->getListStoresByPharmacyId($UserInfo['User']['id']));
        $this->set('pharmacy', $this->Pharmacy->read(null, $UserInfo['User']['id']));
        
	}

	function view($id = null) {
		$sz_BackPharUrl = $this->Session->read('sz_BackPharUrl');
		if( $sz_BackPharUrl )
		{
			$this->Session->delete('sz_BackPharUrl');
			$this->redirect($sz_BackPharUrl);
		}
        $UserInfo = $this->Session->read('User');
		if ( $UserInfo['User']['id'] != $id)
        {
        	$this->redirect(array('controller'=>'errors','action' => 'permission'));
        }
		if (!$id) {
			//$this->redirect(array('controller'=>'errors','action' => 'error404'));
		}
        
        if(empty($UserInfo))
        {
            $this->redirect(array('controller'=>'pages','action' => 'display'));
        }
        
        if($UserInfo['User']['id'] != $id)
        {
            $this->redirect(array('controller'=>'errors','action' => 'error404'));
        }
        $this->set('LastLoggedIn',$UserInfo['User']['LastLoggedIn']);
		$this->set('pharmacy', $this->Pharmacy->read(null, $id));
        $this->set('a_Stores', $this->Store->getListStoresByPharmacyId($id));
        $a_Vacancies = $this->Vacancy->getListVacancy($id);
 
        if($a_Vacancies)
        {
        	$a_Vacancie = $this->Vacancy->find('all',array('conditions'=>array('Vacancy.Pharmacy_id'=>$id,'Vacancy.DateRange <>'=>'')));
       		$this->set('a_Vacancies',$a_Vacancie);
            $a_VacancyId= array();
            foreach($a_Vacancies as $val)
            {
                $a_VacancyId[] =$val['Vacancy']['id'];
            }
            
            $a_VacancyId = implode(',',$a_VacancyId);
            $myApplied = $this->Apply->fGetListMyAppliedByVacancyId($a_VacancyId);
            $this->set('myApplied',$myApplied);
        }
        
	}
	
    function upload_avatar()
    {   
        
        $user = $this->Session->read('User');
        $this->layout =false;
        if($this->data)
        {    
            if(empty($this->data['Pharmacy']['mFile']))
            {
                //required variables are empty
                die ('Please choose a file to upload');
                return;
            }
            
            if($this->data['Pharmacy']['mFile']['error'])
            {
                //File upload error encountered
                die($this->upload_errors($this->data['Locum']['mFile']['error']));
                return;
            }

            $FileName            = strtolower($this->data['Pharmacy']['mFile']['name']); //uploaded file name
            $ImageExt            = substr($FileName, strrpos($FileName, '.')); //file extension
            $FileType            = $this->data['Pharmacy']['mFile']['type']; //file type
            $FileSize            = $this->data['Pharmacy']['mFile']["size"]; //file size
            $RandNumber           = rand(0, 9999999999); //Random number to make each filename unique.
            
            switch(strtolower($FileType))
            {
                //allowed file types
                case 'image/png': //png file
                case 'image/gif': //gif file 
                case 'image/jpeg': //jpeg file
                    break;
                default:
                    die('Unsupported File!');
                    return;
                    break; //output error
            }

          
            //File Title will be used as new File name
            $NewFileName = strtotime(date("Y-m-d H:i:s")).$FileName;
           //Rename and save uploded file to destination folder.
           if(move_uploaded_file($this->data['Pharmacy']['mFile']["tmp_name"], WWW_ROOT.'img/avatar/'. $NewFileName ))
           {
                // resize image
				$this->Image->load(WWW_ROOT.'img/avatar/'. $NewFileName);
		     	$this->Image->resizeToWidth(100);
		     	$this->Image->save(WWW_ROOT.'img/avatar/'. $NewFileName);
				$this->Pharmacy->id    = $user['User']['id'];
				$this->Pharmacy->saveField('Avatar',$NewFileName);

               // Insert info into database table.. do w.e!
               echo '<img src="'. Router::url('/').'app/webroot/img/avatar/'. $NewFileName.'" width="100" height="100" alt="Username">';
                
           }else{
                   die('Error uploading File!');
                   return;
           }
        }
         $this->render(false);
    }
    
	//TODO register user
	function register()
	{
		$this->layout =  null;
	
	}
	
	// save user
    function save(){
        Configure::write('debug', 0);
        $a_Errors = array();
        $b_Error =true;
        $this->layout =  false;
        if(!empty($this->data))
        {  $this->Pharmacy->set($this->data);
           if($this->data['Pharmacy']['Username'] == '')
           {
               $a_Errors["Username"] = "Username is required";
               $b_Error =false;
           }else
           {
               
               if(preg_match("/^[a-z0-9]{4,10}$/i", $this->data['Pharmacy']['Username']) > 0)
                {
                   if($this->Pharmacy->checkUsernameExisted())
                   {
                       $b_Error = $b_Error && true;
                   }else
                   {
                         $a_Errors["Username"] = "Username exist";
                         $b_Error = $b_Error && false;
                   }
                   
                }
                else
                {
                    $a_Errors["Username"] = "Username must be integer and alphabet, between 4-10 characters";
                    $b_Error =$b_Error && false;
                }
           }
           
           if($this->data['Pharmacy']['Password'] == '')
           {
               $a_Errors["Password"] = "Password is required";
               $b_Error =$b_Error && false;
           }
           
           if($this->data['Pharmacy']['Email'] == '')
           {
               $a_Errors["Email"] = "Email is required";
               $b_Error =$b_Error && false;
           }else
           {
                if(preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $this->data['Pharmacy']['Email']) > 0)
                {
                   if($this->Pharmacy->checkEmailExisted())
                   {
                       $b_Error = $b_Error && true;
                   }else
                   {
                         $a_Errors["Email"] = "Email exist";
                         $b_Error = $b_Error && false;
                   }
                }
                else
                {
                    $a_Errors["Email"] = "Email is not validate";
                    $b_Error =$b_Error && false;
                }
           }
           
           if(!$b_Error)
           {    
                $a_Errors["success"]="faild";
                echo json_encode($a_Errors);
           }else
           {
               $sz_Password = $this->data['Pharmacy']['Password'];
               $this->data['Pharmacy']['Password'] = md5($this->data['Pharmacy']['Password']); 
               $this->data['Pharmacy']['UserType'] = 2;
               $this->data['Pharmacy']['IsFirstLogin'] = 1;
               $this->data['Pharmacy']['MatchMemberSince'] = date('Y/m/d');
               if ($this->Pharmacy->save($this->data)) {
               		
               		// Send mail login
               		$a_Email = array();
               		$a_Email["from"] = $GLOBALS['email_template_register']->from;
               		$a_Email["to"] = $this->data['Pharmacy']['Email'];
               		$a_Email["subject"] = $GLOBALS['email_template_register']->subject;
               		$a_Email["content"] = str_replace(
               											array( '__USERNAME__', '__EMAIL__', '__PASSWORD__', '__LINKLOGIN__' ), 
               											array( $this->data['Pharmacy']['Username'], $this->data['Pharmacy']['Email'], $sz_Password, $_SERVER['HTTP_REFERER'] ), 
               											$GLOBALS['email_template_register']->content
               										);
               		$this->sendMail( $a_Email );
               		// End Send mail
               		
                    $a_Errors["success"]="Thank you for your registration please check your inbox for confirmation.";
                    echo json_encode($a_Errors["success"]);
                } else {
                    
                    $a_Errors["success"]="The Pharmacy could not be saved. Please, try again";
                    echo json_encode($a_Errors);
                }
               
           }
           
          
        }
        else 
        {
        	exit('Data Error');
        }
        
        $this->render(false);
    }

    
	function invite( $id = null)
    {
    	$this->set('Locum_id', $id);
    	$this->set('title', "Invite Locum");
		$a_Locum = $this->Locum->getLocumById( $id );
		if ( !$a_Locum )
			$this->redirect(array('controller'=>'errors','action' => 'error404'));
		
		$this->set('a_Locum', $a_Locum);
		// Get list all vacancy
		$a_Vacancy = $this->Vacancy->getListVacancy($this->Session->read('User.User.id'));
		$this->set('a_Vacancy', $a_Vacancy);
    }
    
    function invite_success( $Locum_id, $vacancy_id )
    {
    	$this->set('title', "Invite Locum Successfully");
    	$a_Locum = $this->Locum->getLocumById( $Locum_id );
    	$a_Vacancy = $this->Vacancy->getVacancyById( $vacancy_id );
    	
		if ( !$a_Locum )
			$this->redirect(array('controller'=>'errors','action' => 'error404'));
		
		// Save table invite
		$invite['Invite']['locum_id'] = $Locum_id;
		$invite['Invite']['pharmacy_id'] = $this->Session->read('User.User.id');
		$invite['Invite']['store_id'] = $a_Vacancy['Vacancy']['Store_id'];
		$invite['Invite']['vacancy_id'] = $vacancy_id;
		$invite['Invite']['status'] = 1;
		$this->Invite->create();
		if( $this->Invite->save( $invite ) )
		{
			// Send mail invite
			$a_Email = array();
			$a_Email["from"] = $GLOBALS['email_template_register']->from;
			$a_Email["to"] = $a_Locum['Locum']['Email'];
			$a_Email["subject"] = "Pharmacy Match invitation";
			$a_Email["content"] = "Congratulations, \n";
			$a_Email["content"] .= "A pharmacy has invited you to apply for a vacancy, \n";
			$a_Email["content"] .= "Please log into your PharmacyMatch account and go to the my Invites section for more information. <a href=\" http://". $_SERVER['HTTP_HOST'] . Router::url('/') . "locums/apply/" . $vacancy_id ."\">Click here to log in to your account</a> \n";
			$a_Email["content"] .= "\n\nRegards! \n";
			$this->sendMail( $a_Email );
		}
		$this->set('a_Locum', $a_Locum);
    }
    
    function view_locum_profile($i_LocumId = null)
    {
        if (!$i_LocumId) {
            $this->redirect(array('controller'=>'errors','action' => 'error404'));
        }
        $locum =  $this->Locum->read(null, $i_LocumId);
        $this->set('id',$i_LocumId);
        if(!empty($locum) && $locum['Locum']['UserType'] == 1 )
        {	
            $a_Events = $this->Event->a_fGetEvents($i_LocumId); 
            
            if(!empty($a_Events['Event']['date']))
            {
	            $a_Event = explode(',',$a_Events['Event']['date']);
	            $a_Temps = array();
	            if($a_Event)
	            {
	                foreach($a_Event as $event)
	                {
	                    $a_Temps[] = strtotime($event);
	                }
	            }
	            sort($a_Temps);
	            $i_currentMonth = date('n');
	           // $a_EventMonth = explode('-',date('m'));
	            $i_eventMonth = date('m',$a_Temps[0]);
	            $jump = $i_eventMonth - $i_currentMonth;
	           
	            $this->set('jump',$jump);
            }
            else 
            {
            	$this->set('jump',0);
            	
            }
            
            // Calculate rate job
        	$a_RateJob = $this->Rate->a_fGetRateByLocumId( $i_LocumId );
        	$i_NumberMaxRate = 0;
        	$i_RateAVG = 0;
        	$i_TotalRate = 0; 
        	foreach ( $a_RateJob as $RateJob )
        	{
        		$i_TotalRate += $RateJob['Rate']['rate'];
        		if( $RateJob['Rate']['rate'] == 5 )
        		{
        			$i_NumberMaxRate ++;
        		}
        	}
        	if( count($a_RateJob) > 0 )
        		$i_RateAVG = round( $i_TotalRate/count($a_RateJob) );	
        	
        	$locum['Locum']['i_NumberMaxRate'] = $i_NumberMaxRate;
        	$locum['Locum']['i_RateAVG'] = $i_RateAVG;
            $this->set('locum', $locum);
        }
        else
        {
           $this->redirect(array('controller'=>'errors','action' => 'error404')); 
        }
    }
    
    function getJson($id = null)
    {

         Configure::write('debug', 0);
         $this->autoRender = false;
         $this->layout =  false;
         $sz_StartEvent ='[';
         $sz_EndEvent =']';

         $user = $this->Session->read('User');
         if($user)
         {
           $a_Events = $this->Event->a_fGetEvents($id); 

           if($a_Events)
           {
               $a_Event = explode(',',$a_Events['Event']['date']);
               $i=1;
               $n= count($a_Event);
               foreach($a_Event as $k=>$event){
                  if($i < $n)
                    $sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($event)).'"'.'},';
                  else
                     $sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($event)).'"'.'}';
                  $i++;
               }
           }
           
         }
       
          
        echo $sz_StartEvent.$sz_EndEvent;
        $this->render(false);
    }
    
    function view_store($id = null) {
        
        $UserInfo = $this->Session->read('User');
        if(empty($UserInfo) || $UserInfo['User']['UserType'] != 2)
        {
            $this->redirect(array('controller'=>'pages','action' => 'display'));
        }
      
        if (!$id) {
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'index'));
        }
         
        $a_Stores =$this->Store->a_fGetStoresByPharmacyIdAndStoreId($UserInfo['User']['id'], $id);
        if(!empty($a_Stores)){
            $this->set('a_Stores', $a_Stores);
             }
        else
        {
            
            $this->redirect(array('controller'=>'errors','action' => 'error404'));
        }
    }
    
    function view_applied($id = null)
    {
    
        $UserInfo = $this->Session->read('User');
        if(empty($UserInfo) || $UserInfo['User']['UserType'] != 2)
        {
            $this->redirect(array('controller'=>'pages','action' => 'display'));
        }
       $appliedDetail = $this->Apply->fGetListMyAppliedByApplyId($id);
       
       if(!empty($appliedDetail)){
             
       	
       		if(!empty($appliedDetail['Apply']['available']))
       		{
	            $a_Event = explode(',',$appliedDetail['Apply']['available']);
	            $a_Temps = array();
	            if($a_Event)
	            {
	                foreach($a_Event as $event)
	                {
	                    $a_Temps[] = strtotime($event);
	                }
	            }
	            sort($a_Temps);
	            $i_currentMonth = date('n');
	           // $a_EventMonth = explode('-',date('m'));
	            $i_eventMonth = date('m',$a_Temps[0]);
	            $jump = $i_eventMonth - $i_currentMonth;
       		}else 
       		{
       			
       			$jump =0;
       		}
           
            $this->set('jump',$jump);
            $this->set('appliedDetail', $appliedDetail);
       }
        else
        {  
            $this->redirect(array('controller'=>'errors','action' => 'error404'));
        }
    }
    
    function accepted($id = null)
    {

        $UserInfo = $this->Session->read('User');
        $this->Apply->id    = $id;
        $this->Apply->saveField('status',2);
        
        $applied = $this->Apply->applideDateRage($id);  
        //Update to event date
        $event =  $this->Event->a_fGetEvents($applied['Apply']['locum_id']);
        if($event['Event']['date'])
       		 $event['Event']['date'].=','.$applied['Apply']['available'];
        else 
        	$event['Event']['date'] = $applied['Apply']['available'];
        $this->Event->id =$event['Event']['id'];
        $this->Event->saveField('date',$event['Event']['date']);
        //Remove date of vacancy date
         
         $a_Vacancy = $this->Vacancy->getVacancyById( $applied['Apply']['vacancy_id'] );
        
    	 $DateRange = explode(',',$a_Vacancy['Vacancy']['DateRange']);
         $DateRangeRemove = explode(',',$applied['Apply']['available']);
        
         $DateRangeDiff = array_diff ($DateRange, $DateRangeRemove); 
         if($DateRangeDiff)
         {
             $sz_DateRangeDiff =implode(',',$DateRangeDiff);
               
         }else
         {
              $sz_DateRangeDiff ='';
         }
      
        $this->Vacancy->id = $applied['Apply']['vacancy_id'];
		$this->Vacancy->saveField('DateRange',$sz_DateRangeDiff);
		
        $locum = $this->Locum->getLocumById($applied['Apply']['locum_id']);
         // Send email to locum
        $a_Email = array();
        $a_Email["from"] = $GLOBALS['email_template_register']->from;
        $a_Email["to"] = $locum['Locum']['Email'];
        $a_Email["subject"] = "Applied vacancy successfully";
        $sz_LinkApplication = 'http://' . $_SERVER['HTTP_HOST'] . Router::url('/') . 'locums/view_apply/' . $id;
        $sz_Content = "The Pharmacy accepted your apply vacancy. \n";
        $sz_Content .= "Please click <a href='" . $sz_LinkApplication ."'>here</a> to view details of this application";
        $a_Email["content"] = $sz_Content;
        $this->sendMail( $a_Email );
        $this->redirect(array('controller'=>'pharmacies','action' => 'applicants/'.$UserInfo['User']['id']));
    }
    
    function decline($id = null)
    {
         $this->Apply->id    = $id;
         $this->Apply->saveField('status',3);
         $UserInfo = $this->Session->read('User');
         // Send mail Locum

        $applied = $this->Apply->applideDateRage($id);
        $locum = $this->Locum->getLocumById($applied['Apply']['locum_id']);
         // Send email to locum
        $a_Email = array();
        $a_Email["from"] = $GLOBALS['email_template_register']->from;
        $a_Email["to"] = $locum['Locum']['Email'];
        $a_Email["subject"] = "Decline applicant";
        $sz_LinkApplication = 'http://' . $_SERVER['HTTP_HOST'] . Router::url('/') . 'locums/view_apply/' . $id;
        $sz_Content = "Hi {$locum['Locum']['Username']},\n" ;
        
        $sz_Content .= "You've been declined in <a href='" . $sz_LinkApplication ."'>this applicant</a>\n";
        $sz_Content .= "\n\n\nRegards,";
        $a_Email["content"] = $sz_Content;
        $this->sendMail( $a_Email );
         $this->redirect(array('controller'=>'pharmacies','action' => 'applicants/'.$UserInfo['User']['id']));
    }
    
    function applicants(){
        
        $UserInfo = $this->Session->read('User');
        if(empty($UserInfo) || $UserInfo['User']['UserType'] != 2)
        {
            $this->redirect(array('controller'=>'pages','action' => 'display'));
        }
        
        $this->paginate['Vacancy'] = array(
                    'limit' => 10
                    ,'contain' => ''
                    ,'conditions' => array(
                             'Vacancy.Pharmacy_id' => $UserInfo['User']['id']
                    ), 'fields' => array('Vacancy.*','Apply.*','User.*'), 
                    'joins' => array(
                        array(
                            'table' => 'applies'
                            ,'type' => 'INNER'
                            ,'alias' => 'Apply'
                            ,'conditions' => array(
                            'Vacancy.id = Apply.vacancy_id'
                            )
                        ), 
                        array(
                            'table' => 'users'
                            , 'alias' => 'User'
                            , 'type' => 'INNER'
                            , 'conditions' => array(
                                "Apply.locum_id = User.id"
                            )
                        )
                    )
        );
        $data = $this->paginate('Vacancy');
        $this->set(compact('data'));
    }
    
    function rate($id = null)
    {   
        $applied = $this->Apply->applideDateRage($id); 
 
        $this->set('applied',$applied);
        $UserInfo = $this->Session->read('User');
        $this->set('pharmacy', $this->Pharmacy->read(null, $UserInfo['User']['id']));
        $this->set('locum', $this->Locum->read(null, $applied['Apply']['locum_id']));
        if($this->data)
        {
            $aRate =array(
                'rate' =>$this->data['Pharmacy']['rate'],
                'pharmacy_id' =>$UserInfo['User']['id'],
                'locum_id'    =>$this->data['Pharmacy']['locum_id'],
                'vacancy_id'    =>$this->data['Pharmacy']['vacancy_id']
            );
            
            $this->Rate->create();
            $this->Rate->set($aRate);
            if($this->Rate->save($aRate))
            {
                $this->Apply->id = $this->data['Pharmacy']['id'];
                $this->Apply->saveField('rate',1);
                $this->redirect(array('controller'=>'pharmacies','action' => 'view','id'=>$UserInfo['User']['id']));
            }
                
        }  
    }
    
	function getJsonApply($id = null)
    {
        Configure::write('debug', 0);
        $this->autoRender = false;
        $this->layout =  false;
        $sz_StartEvent ='[';
        $sz_EndEvent =']';
        $this->set('id',$id);
        $a_Events = $this->Apply->applideDateRage($id); 
        if($a_Events)
        {
           $a_EventsVacancy = $this->Vacancy->find('first',array('fields'=>'DateRange','conditions'=>array('id'=>$a_Events['Apply']['vacancy_id']))); 
	        if($a_EventsVacancy['Vacancy']['DateRange'])
	        {
	           $a_EventVacancy = explode(',',$a_EventsVacancy['Vacancy']['DateRange']);
	           $a_EventVacancy = array_unique($a_EventVacancy);
	           $i=1;
	           $n= count($a_EventVacancy);
	           foreach($a_EventVacancy as $k=>$e){
	              if($i < $n)
	                $sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($e)).'"'.'},';
	              else
	                 $sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($e)).'"'.'}';
	              $i++;
	           }
	           
	           $a_Event = explode(',',$a_Events['Apply']['available']);
	           $a_Event = array_unique($a_Event);
	           $i=1;
	           $n= count($a_Event);
	           foreach($a_Event as $k=>$event){
	              if($i < $n)
	                $sz_StartEvent .= ',{"date2": '.'"'.date('Y-m-d',strtotime($event)).'"'.'}';
	              else
	                 $sz_StartEvent .= ',{"date2": '.'"'.date('Y-m-d',strtotime($event)).'"'.'}';
	              $i++;
	           }
	        }else 
	        {
		         $a_Event = explode(',',$a_Events['Apply']['available']);
		           $a_Event = array_unique($a_Event);
		           $i=1;
		           $n= count($a_Event);
		           foreach($a_Event as $k=>$event){
		              if($i < $n)
		                $sz_StartEvent .= '{"date2": '.'"'.date('Y-m-d',strtotime($event)).'"'.'},';
		              else
		                 $sz_StartEvent .= '{"date2": '.'"'.date('Y-m-d',strtotime($event)).'"'.'}';
		              $i++;
		           }
	        }
           
           
           
        }


        echo $sz_StartEvent.$sz_EndEvent;
        $this->render(false);
    }
    
    function getJsonVacancy($id = null)
    {
        Configure::write('debug', 0);
        $this->autoRender = false;
        $this->layout =  false;
        $sz_StartEvent ='[';
        $sz_EndEvent =']';
        $this->set('id',$id);
        $a_Events = $this->Vacancy->find('first',array('fields'=>'DateRange','conditions'=>array('id'=>$id))); 
        if($a_Events)
        {
           $a_Event = explode(',',$a_Events['Vacancy']['DateRange']);
           $a_Event = array_unique($a_Event);
           $i=1;
           $n= count($a_Event);
           foreach($a_Event as $k=>$event){
              if($i < $n)
                $sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($event)).'"'.'},';
              else
                 $sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($event)).'"'.'}';
              $i++;
           }
        }


        echo $sz_StartEvent.$sz_EndEvent;
        $this->render(false);
    }
}
?>